package com.ctgu.controller;

import com.ctgu.entity.Product;
import com.ctgu.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
//    @Qualifier("ProductServiceImpl")
    private ProductService productService;
    int sort_1;
    int cnt_1;
    //分类搜索
    @RequestMapping("sort")
    public String sort(Model model, int  sort1){
        List<Product> list = productService.findBySort1(sort1);
        sort_1 = sort1;
    //        request.getSession().setAttribute("sort1",sort1);
        model.addAttribute("product_list",list);
        return "list";
    }

    //搜索框以名称和类别进行搜索
    @RequestMapping("search")
    public String Search(String name,Model model){
        List<Product> list = productService.findByName(name);
        if(list.size()==0){
            model.addAttribute("error","block");
            model.addAttribute("no","none");
        }else{
            cnt_1=1;
            model.addAttribute("product_list",list);
            model.addAttribute("no","block");
        }
        return "list";
    }

    //登录用户后，统计该用户购物车内的商品数目
    @RequestMapping("login")
    public String login(HttpServletRequest request){
        int number=productService.countShopping();
        request.getSession().setAttribute("number",number);
        return "index";
    }

    @RequestMapping("ordinary")
    public String ordinary(Model model,int cnt){

        List<Product> list = null;
//        int sort = (int) request.getSession().getAttribute("sort1");
        int sort;

        if(cnt_1==1)
            sort = 1;
        else
            sort= sort_1;

        if(cnt==0){
            list = productService.findBySort1(sort);
        }else if(cnt==1){
            list = productService.sortByPopularity(sort);
        }else if(cnt==2){
            list = productService.sortByPrice(sort);
        }
        model.addAttribute("product_list",list);
        return "list";
    }

}
